#!/user/bin/env python
# -*- coding: utf-8 -*-
# @Software: PyCharm
# @Time : 2021/05/12 10:14
# @Author : ziqi.zhang
# @Version : 1.0.0
# @Description : 测试用例Demo，业务的实例

import ddt
import logging
import unittest
from Common.Excel import Excel
from Common.Base import Driver
from Common.Logging import Logging
from Business.BaiduSearch_Business import BaiduSearchBusiness

# ddt，数据准备
data = Excel().excel()

# 实例日志类
Logging()


# 给addCleanup使用的方法
def clean():
    logging.info("清理环境完成")


@ddt.ddt
class TestRun(unittest.TestCase):
    driver = None

    @classmethod
    def setUpClass(self):
        """所有用例开始前执行"""
        logging.info("开始测试，使用Chrome浏览器")  # 所有用例开始前打印
        self.driver = Driver("chrome")  # 调用Common文件夹中Common.py文件的Driver()初始化
        self.driver.maximize_window()  # 窗口最大化

    @classmethod
    def tearDownClass(self):
        """所有用例结束后执行"""
        logging.info("结束测试")  # 所有用例完成后打印
        self.driver.close()  # 关闭浏览器
        self.driver.quit()  # 关闭driver

    def setUp(self):
        """每个用例开始时执行"""
        pass

    def tearDown(self):
        """每个用例结束后执行"""
        self.addCleanup(clean)  # 清理环境

    @ddt.data(*data)  # 拿到excel中的数据
    def test_Baidusearch(self, data):
        searchWork, searchResult = data  # excel中搜索的关键词和预期结果
        """百度搜索业务逻辑用例"""
        try:
            result_text = BaiduSearchBusiness(self.driver).ass(searchWork)  # 实际结果
            assert (searchResult in result_text)  # 预期结果与实际结果比较作断言
            logging.info('Pass')
        except Exception as e:
            logging.error('Failed', exc_info=True)
            raise

    def test_001(self):
        """用例通过例子：pass"""
        try:
            assert ('百度一下' in '百度一下')
            logging.info("Pass")
        except Exception as e:
            logging.error("Failed", exc_info=True)
            raise

    def test_002(self):
        """用例失败例子：failed"""
        try:
            assert ('百度一下！' in '123')
            logging.info("Pass")
        except Exception as e:
            logging.error("Failed", exc_info=True)
            raise

    def test_003(self):
        """用例错误例子：error"""
        try:
            assert ('百度一下' in self.driver.by_xpath('//*[@id="su"]/span').text)
            logging.info("Pass")
        except Exception as e:
            logging.error("Failed", exc_info=True)
            raise
